<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Http\Model\User;
use App\Http\Model\Comment;
use App\Http\Model\Record;
use App\Http\Model\Fenxiao;
use App\Http\Model\Orders;
use App\Http\Model\OrdersInfo;
use App\Http\Model\IntegralOrders;
use App\Http\Model\ClothingAttr;
use App\Http\Model\Company;
use DB;

class IndexController extends Controller
{
    //
    public function index(){
        // dd($this->get_used_status());
        // dd(111);
    	$user = new User;
    	$data = array();
    	$data['sumSalePrice'] = 0;
    	$userInfo = $user->select("user.*", DB::raw('sum(orders_info.num) as sum'))->leftJoin("orders", "user.id", "=", "user_id")->leftJoin("orders_info", "orders.id", "=", "orders_id")->groupBy("user.id")->orderBy("sum", "desc")->get();
    	$data['monthSalePrice'] = $this->getMonthSalePrice(date("Y-m"));
    	$data['prevMonthSalePrice'] = $this->getMonthSalePrice(date('Y-m',strtotime(date('Y',time()).'-'.(date('m',time())-1).'-01')));
    	for ( $i=1; $i<13; $i++){
    		$month = $i<10 ? date("Y")."-0".$i : date("Y")."-".$i;
    		$data["$i"] = $this->getMonthSalePrice($month);
    		$data['sumSalePrice'] += $data["$i"];
    	}

    	$data['avgSalePrice'] = $data['sumSalePrice'] / date("m");
    	return view("admin.index.index", ['userInfo'=>$userInfo,'data'=>$data]);
    }
    public function getMonthSalePrice($month){
    	$orders = new Orders;
    	$clothingAttr = new ClothingAttr;
    	$monthSale = $orders->select("orders_info.id", "orders_info.clothing_attr_id", "orders_info.num","orders_info.price")->leftJoin("orders_info", "orders.id", "=", "orders_id")->where("orders.created_at", "like", "%".$month."%")->where("status", ">", "3")->get();
    	$monthSalePrice = 0;
    	foreach ($monthSale as $k => $v) {
    		$monthSalePrice += $v->price * $v->num;
    	}
    	return $monthSalePrice;
    }
    public function get_used_status(){
        $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况
        $rs = "";
        while(!feof($fp)){
            $rs .= fread($fp,1024);
        }
        pclose($fp);
        $sys_info = explode("\n",$rs);

        $tast_info = explode(",",$sys_info[3]);//进程 数组
        $cpu_info = explode(",",$sys_info[4]);  //CPU占有量  数组
        $mem_info = explode(",",$sys_info[5]); //内存占有量 数组

        //正在运行的进程数
        $tast_running = trim(trim($tast_info[1],'running'));
        //CPU占有量
        $cpu_usage = trim(trim($cpu_info[0],'Cpu(s): '),'%us') * 100 ."%";  //百分比

        //内存占有量
        $mem_total = trim(trim($mem_info[0],'Mem: '),'k total');
        $mem_used = trim($mem_info[1],'k used');
        $mem_usage = "内存占用率：".round(100*intval($mem_used)/intval($mem_total),2)."%";  //百分比


        /*硬盘使用率 begin*/
        $fp = popen('df -lh | grep -E "^(/)"',"r");
        $rs = fread($fp,1024);
        pclose($fp);
        $rs = preg_replace("/\s{2,}/",' ',$rs);  //把多个空格换成 “_”
        $hd = explode(" ",$rs);
        $hd_avail = "磁盘可用空间：".$hd[3]; //磁盘可用空间大小 单位G
        $hd_usage = "磁盘使用率：".$hd[4]; //挂载点 百分比
        //print_r($hd);
        /*硬盘使用率 end*/

        //检测时间
        $fp = popen("date +\"%Y-%m-%d %H:%M\"","r");
        $rs = fread($fp,1024);
        pclose($fp);
        $detection_time = trim($rs);

        return  array('cpu_usage'=>$cpu_usage,'mem_usage'=>$mem_usage,'hd_avail'=>$hd_avail,'hd_usage'=>$hd_usage,'tast_running'=>$tast_running,'detection_time'=>$detection_time);
    }

    public function reback(){
        $orders = new Orders;
        $ordersInfo = new OrdersInfo;
        $fenxiao = new Fenxiao;
        $record = new Record;
        //查询分销相关数据
        $fenxiaoData = $fenxiao->first();
        $reMoney=array();
        $money = array();
        $reMoney[0]=$fenxiaoData->re_money_1;
        $reMoney[1]=$fenxiaoData->re_money_2;
        $reMoney[2]=$fenxiaoData->re_money_3;
        $reMoney[3]=$fenxiaoData->re_money_4;
        $reMoney[4]=$fenxiaoData->re_money_5;
        $money[0] = $fenxiao->money_1;
        $money[1] = $fenxiao->money_2;
        $money[2] = $fenxiao->money_3;
        $money[3] = $fenxiao->money_4;
        $money[4] = $fenxiao->money_5;
        $reCode = $fenxiaoData->re_code_1;
        $reBusiness = $fenxiaoData->re_money_business;
        $standard = $fenxiaoData->re_money_1;

        //查询本月用户以及订单信息
        $upOrdersInfo = $orders->select('orders.id')->leftJoin('user','user.id','=','user_id')->where("status",">",3)->where('re_status','0')->get();
        $ordersInfo_temp = $orders->select('user_id','identity')->leftJoin('user','user.id','=','user_id')->where("status",">",3)->where('re_status','0')->groupBy('user_id')->get();

        foreach($ordersInfo_temp as $key=>$value){
        	$userCount = $this->saleVolume($value->user_id,$value->identity);
        	if(is_array($userCount)){
        		if($userCount['member']){
        			$record = new Record;
        			foreach ($money as $k1 => $v1) {
        				if($userCount['member']>$v1 &&($v1!='0' || $k1=='0')){
        					$standard = $reMoney[$k1];
        				}else{
        					break;
        				}
        			}
                    $record->remoney = $userCount['member']*$standard*0.01;
                    $record->recount = $userCount['member'];
                    $record->user_id = $value->user_id;
                    $record->percent = $standard.'%';
                    $record->retime = substr($value->created_at,0,7);

                    $user = new User;
                    $userInfo = $user->find($value->user_id);
                    $userInfo->money += $record->remoney;
                    $res = $record->save();
        		}
        		if($userCount['business']){
        			$record = new Record;
                    $record->remoney = $userCount['business']*$reBusiness*0.01;
                    $record->recount = $userCount['business'];
                    $record->user_id = $value->user_id;
                    $record->percent = $reBusiness.'%';
                    $record->retime = substr($value->created_at,0,7);

                    $user = new User;
                    $userInfo = $user->find($value->user_id);
                    $userInfo->money += $record->remoney;
                    $this->rebackTemplate($userInfo,$record->money);
                    $res = $record->save();
                    $userInfo->save();
        		}
        	}else if($userCount){
        		$record = new Record;
                $record->record = $userCount*$reCode*0.01;
                $record->recount = $userCount;
                $record->user_id = $value->user_id;
                $record->percent = $reCode.'%';
                $record->retime = substr($value->created_at,0,7);

                $user = new User;
                $userInfo = $user->find($value->user_id);
                $userInfo->integral += $record->record;

                $res = $record->save();
                $userInfo->save();
        	}
        }
        foreach ($upOrdersInfo as $k2 => $v2) {
        	$order = new Orders;
        	$upOrder = $order->find($v2->id);
            $upOrder->re_status = 1;
        	$upOrder->receipt_at = date("Y-m-d H:i:s");
        	$upOrder->save();
        }
    }


    // 未读评论，发货提醒，兑换发货提醒
    public static function getTips(){
        $comment = new Comment;
        $orders = new Orders;
        $user = new User;
        $integralOrders = new IntegralOrders;
        $data['commentInfo'] = $comment->where("status", 0)->skip(0)->take(5)->get();
        $data['ordersInfo'] = $orders->where("status", 2)->skip(0)->take(5)->get();
        $data['integralOrdersInfo'] = $integralOrders->where("status", 0)->skip(0)->take(5)->get();
        $data['fenxiao'] = $user->where("distributor_status", 1)->skip(0)->take(5)->get();
        // dd($data);
        return $data;
    }
    public function skinConfig(){
        return view("admin.index.skin-config");
    }
    //关于公司
    public function company(){
        $company = new Company;
        $companyInfo = $company->find(1);
        return view("admin.index.company",['companyInfo'=>$companyInfo]);
    }
    public function editCompany(Request $request){
        $company = new Company;
        $companyInfo = $company->find($request->input('id'));
        $companyInfo->company = $request->input('company');
        $companyInfo->save();
        return redirect('admin/company')->with('success','关于公司编辑成功！');
    }
    //线下门店
    public function store(){
        $company = new Company;
        $storeInfo = $company->find(2);
        return view("admin.index.store",['storeInfo'=>$storeInfo]);
    }
    public function editStore(Request $request){
        $company = new Company;
        $storeInfo = $company->find($request->input('id'));
        $storeInfo->content = $request->input('content');
        $storeInfo->save();
        return redirect('admin/store')->with('success','线下门店编辑成功！');
    }
}